package com.guigu.youxuan.controller;

import com.guigu.youxuan.pojo.BackMenu;
import com.guigu.youxuan.service.IBackMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author liweixin
 * @since 2024-05-15
 */
@CrossOrigin
@RestController
@RequestMapping("/backMenu")
public class BackMenuController {

    @Autowired
    private IBackMenuService backMenuService;

    @RequestMapping("/queryBackMenuList")
    public List<BackMenu> queryBackMenuList() {
        List<BackMenu> backMenuList = backMenuService.queryBackMenuList();

        //菜单分层
        List<BackMenu> finalBackMenuList = new ArrayList<>();
        //处理一级菜单及其下的子菜单
        for (BackMenu menu : backMenuList) {
            if (menu.getLevel() == 1) {
                // 二级菜单列表
                List<BackMenu> children = new ArrayList<>();
                // 查找并添加二级菜单
                for (BackMenu subMenu : backMenuList) {
                    if (subMenu.getLevel() == 2 && subMenu.getParentId().equals(menu.getId())) {
                        // 三级菜单列表
                        List<BackMenu> grandChildren = new ArrayList<>();
                        // 查找并添加三级菜单
                        for (BackMenu grandSubMenu : backMenuList) {
                            if (grandSubMenu.getLevel() == 3 && grandSubMenu.getParentId().equals(subMenu.getId())) {
                                grandChildren.add(grandSubMenu);
                            }
                        }
                        // 设置二级菜单的子菜单
                        subMenu.setChildren(grandChildren);
                        children.add(subMenu);
                    }
                }
                // 设置一级菜单的子菜单
                menu.setChildren(children);
                // 添加到最终列表
                finalBackMenuList.add(menu);
            }
        }
        return finalBackMenuList;
    }
}
